import binascii
import gb2312
import framebuf
import time
import ssd1306

class OLEDController:
    
    def __init__(self, oled, font_size=2):
        self.font_size = font_size  # 添加字体大小变量
        self.oled = oled
        self.buf = bytearray(128 * 64 // 8)
        #self.fb = framebuf.FrameBuffer(self.buf, 128, 64, framebuf.MONO_HLSB)
        self.KEYS = [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]
        self.rect_list = [[] for _ in range(16)]
        self.gb2312 =gb2312.fontbyte
        self.font_file = open("HZK16", "rb")
       
    def fill(self,fillcoler=0):
        self.oled.fill(0)
        
    def display_char(self, char, x, y):
        try:
            self.display_chinese(char, x, y)
        except:
            self.oled.text(char, x, y)
        #self.oled.blit(self.fb, 0, 0)
        #self.oled.show()

    def display_chinese(self, char, x, y):
        starttime = time.time_ns()
        self.rect_list = [[] for _ in range(16)]       
        get_gb2312 = self.gb2312.strs(char)
        #print("gb2312 查找耗时",(time.time_ns()-starttime)/1e9)

        starttime = time.time_ns()
        hex_str = binascii.hexlify(get_gb2312).decode('utf-8')
        area = eval('0x' + hex_str[:2]) - 0xA0
        index = eval('0x' + hex_str[2:]) - 0xA0
        offset = (94 * (area-1) + (index-1)) * 32

        font_rect = None
        #with open("HZK16", "rb") as f:
         #   f.seek(offset,0)
          #  font_rect = f.read(32)
        self.font_file.seek(offset,0)
        font_rect = self.font_file.read(32)
        #print("HZK16 查找耗时",(time.time_ns()-starttime)/1e9)
        
        for k in range(len(font_rect) // 2):
            row_list = self.rect_list[k]
            for j in range(2):
                for i in range(8):
                    asc = font_rect[k * 2 + j]
                    flag = asc & self.KEYS[i]
                    row_list.append(flag)

        # 计算新的字体大小
        new_font_size = self.font_size // 2
        for row in range(len(self.rect_list)):
            for col in range(len(self.rect_list[0])):
                if self.rect_list[row][col]:
                    #self.oled.fill_rect(x + col * new_font_size, y + row * new_font_size, new_font_size, new_font_size, 1)
                    self.oled.pixel(x + col * new_font_size, y + row * new_font_size, 1)

    def text(self, text, x=0, y=0):
        for index, char in enumerate(text):
            self.display_chinese(char, x + index * self.font_size*8, y)

